package com.xiaominge.utils.pdf;

import com.xiaominge.exception.ParameterRuntimeException;
import org.apache.pdfbox.pdmodel.PDDocument;

import java.io.File;
import java.io.IOException;

/**
 * @program: system_platform
 * @description: PdfUtils
 * @author: xiaominge
 * @create: 2021-01-13 16:49
 **/

public class PdfUtils {

    private  volatile static PdfUtils pdfUtils;

    public static PdfUtils getPUtils() {
        if (pdfUtils == null) {
            synchronized (PdfUtils.class) {
                if (pdfUtils == null) {
                    pdfUtils = new PdfUtils();
                }
            }
        }
        return pdfUtils;
    }

    public int getPdfTotalSize(File file) {

        if (file == null) {
            ParameterRuntimeException.throwException("文件不能为空");
        }
        String fileName = file.getName();
        String filePostFix= fileName.substring(fileName.lastIndexOf(".") + 1);

        if (!"pdf".equalsIgnoreCase(filePostFix)) {

            ParameterRuntimeException.throwException("不是pdf文件,无法获取总页数");
        }
        PDDocument pdfReader = null;
        try {
            pdfReader = PDDocument.load(file);
        } catch (IOException e) {
            e.printStackTrace();
            ParameterRuntimeException.throwException("不是pdf文件,无法获取总页数");

        }
        int numberOfPages = pdfReader.getNumberOfPages();
        try {
            pdfReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                pdfReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return numberOfPages;
    }
}
